#!/usr/bin/env python
#coding:utf-8
#
# automatically take snapshots for flvs
#
import urllib2
from subprocess import call
import re
from include import common
import os

def useproxy(proxy='http://localhost:3128'):
    proxies = {'http':proxy}
    proxy_support = urllib2.ProxyHandler(proxies)
    opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
    urllib2.install_opener(opener)

def geturl(vid):
	url = 'http://v.iask.com/v_play.php?vid=%s' % str(vid)
	xml = urllib2.urlopen(url).read()
	m = re.compile('http://.*?flv').findall(xml)
	if m:
		return m[-1]
	else:
		return None

def snap(url):
	flv = urllib2.urlopen(url).read(1024*512)
	fname = '/tmp/%s' % url.rsplit('/',1)[1]
	picname = fname[:-3] + 'jpg'
	open(fname,'wb').write(flv)
	cmd = 'ffmpeg -y -i %s -vframes 1 -ss 2 -an -vcodec mjpeg -f rawvideo -s 120x90 %s' % (fname,picname)
	call(cmd.split(' '))
	return open(picname,'rb').read()

def fetch(last=None):
	c = common.getdb().cursor()
	if not last:
		last = 65535
	c.execute('''select id from ac_threads
			where osite!="bilibili" and category != "文章"
			order by id desc limit %s''',(last,))
	ids = [ x[0] for x in c.fetchall() ]
	for id in ids:
		try:
			print id
			sid = str(id)
			jpgname = common.PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
			if os.path.exists(jpgname) and os.path.getsize(jpgname):
				continue
			c.execute('''select vvid,flashvars from ac_parts where partid=%s''',
				(id+0.001,))
			x = c.fetchone()
			if not x:
				print '!! no part',id
				continue
			vvid,flashvars = x
			if 'file=' in flashvars:
				start = flashvars.find('file=')
				end = flashvars[start:].find('&')
				if end == -1:
					end = 65535
				url = flashvars[start+5:end]
				if '?' in url and 'flv' in url:
					url = url[:url.find('?')]
			elif 'type=youku' in flashvars:
				# parse youku to be done
				continue
			else:
				url = geturl(vvid)
			print vvid,url
			jpg = snap(url)
			if len(jpg):
				print '--',jpgname
				common.ensure_dir(jpgname)
				open(jpgname,'wb').write(jpg)
		except Exception as what:
			open('error','a').write(repr(what)+'\n')	

if __name__ == '__main__':
	#useproxy()
	fetch(50)
